﻿using System;
using System.ComponentModel;
using System.Text;
using SymbolicLinkManageCore;

namespace SymbolicLinkManageUI.Library
{
    public class LogManage : ILogManage, INotifyPropertyChanged
    {
        public static LogManage Instance { get; private set; } = new LogManage();

        public event PropertyChangedEventHandler? PropertyChanged;
        private StringBuilder m_Cache = new StringBuilder(5000);
        public StringBuilder Cache => m_Cache;
        private void NotifyCacheChanged() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Cache)));
        private void internalClear() { Cache.Clear(); NotifyCacheChanged(); }
        private void internalWriteNewInfo(string text) { if (string.IsNullOrEmpty(text)) return; Cache.Append(text); NotifyCacheChanged(); }
        private void internalWriteLineNewInfo(string text) { if (string.IsNullOrEmpty(text)) return; Cache.AppendLine(text); NotifyCacheChanged(); }
        private void internalWriteExceptionInfo(string OwnerInfo, Exception? exception)
        {
            if (string.IsNullOrEmpty(OwnerInfo) && exception == null)
                return;
            Cache.AppendLine(OwnerInfo);
            while (exception != null)
            {
                Cache.AppendLine(exception.Message);
                Cache.AppendLine(exception.StackTrace);
                exception = exception.InnerException;
            }
            NotifyCacheChanged();
        }


        public void LogClear() => internalClear();
        public void LogWriteNewInfo(string text, bool ForceWrite = false) { if (ForceWrite || Config.IsEnableWriteLog) internalWriteNewInfo(text); }
        public void LogWriteLineNewInfo(string text, bool ForceWrite = false) { if (ForceWrite || Config.IsEnableWriteLog) internalWriteLineNewInfo(text); }
        public void LogWriteExceptionInfo(string OwnerInfo, Exception exception, bool ForceWrite = true) { if (ForceWrite || Config.IsEnableWriteLog) internalWriteExceptionInfo(OwnerInfo, exception); }


        public static void Clear() => Instance.internalClear();
        public static void WriteNewInfo(string text, bool ForceWrite = false) => Instance.LogWriteNewInfo(text, ForceWrite);
        public static void WriteLineNewInfo(string text, bool ForceWrite = false) => Instance.LogWriteLineNewInfo(text, ForceWrite);
        public static void WriteExceptionInfo(string OwnerInfo, Exception exception, bool ForceWrite = true) => Instance.LogWriteExceptionInfo(OwnerInfo, exception, ForceWrite);
    }
}
